package cn.antblog.jvm.juc;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName Lock
 * @Description TODO
 * @Author YangJingyi
 * @Date 2023/8/2 15:41
 * @Version 1.0
 */
public class TestLock {
//    public static void main(String[] args) throws InterruptedException {
//        Lock testLock = new ReentrantLock();
//        Condition condition = testLock.newCondition();
//        new Thread(() -> {
//            testLock.lock();   //和synchronized一样，必须持有锁的情况下才能使用await
//            System.out.println("线程1进入等待状态！");
//            try {
//                condition.await();   //进入等待状态
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println("线程1等待结束！");
//            testLock.unlock();
//        }).start();
//        Thread.sleep(100); //防止线程2先跑
//        new Thread(() -> {
//            testLock.lock();
//            System.out.println("线程2开始唤醒其他等待线程");
//            condition.signal();   //唤醒线程1，但是此时线程1还必须要拿到锁才能继续运行
//            System.out.println("线程2结束");
//            testLock.unlock();   //这里释放锁之后，线程1就可以拿到锁继续运行了
//        }).start();
//    }

//    public static void main(String[] args) throws InterruptedException {
//        ReentrantLock lock = new ReentrantLock();
//        lock.lock();
//        lock.lock();
//        System.out.println("当前加锁次数："+lock.getHoldCount()+"，是否被锁："+lock.isLocked());
//        TimeUnit.SECONDS.sleep(1);
//        lock.unlock();
//        System.out.println("当前加锁次数："+lock.getHoldCount()+"，是否被锁："+lock.isLocked());
//        TimeUnit.SECONDS.sleep(1);
//        lock.unlock();
//        System.out.println("当前加锁次数："+lock.getHoldCount()+"，是否被锁："+lock.isLocked());
//    }


    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        Thread t1 = new Thread(lock::lock), t2 = new Thread(lock::lock);;
        t1.start();
        t2.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("当前等待锁释放的线程数："+lock.getQueueLength());
        System.out.println("线程1是否在等待队列中："+lock.hasQueuedThread(t1));
        System.out.println("线程2是否在等待队列中："+lock.hasQueuedThread(t2));
        System.out.println("当前线程是否在等待队列中："+lock.hasQueuedThread(Thread.currentThread()));
    }



}
